package com.jz.community.modulemine.message.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.constant.Constant;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.message.bean.MessageListBean;
import com.jz.community.modulemine.message.presenter.MessagePresenter;
import com.jz.community.modulemine.packet.ui.activity.RedPacketActivity;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouterIntentConstant.PUSH_MESSAGE)
public class MessageActivity extends BaseMvpActivity<MessageView.View, MessagePresenter> implements MessageView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R2.id.user_message_back)
    ImageView userMessageBack;
    @BindView(R2.id.user_message_detail)
    TextView userMessageDetail;
    @BindView(R2.id.user_message_title)
    TextView userMessageTitle;
    @BindView(R2.id.user_message_toolbar)
    Toolbar userMessageToolbar;
    @BindView(R2.id.user_message_rv)
    RecyclerView userMessageRv;
    @BindView(R2.id.user_message_refresh)
    SmartRefreshLayout userMessageRefresh;

    private View noDataView;//无数据显示
    private View errorView;//网络错误显示
    private View loadingView;//加载显示

    //页数
    private int page = 0;
    //每页数量
    private int size = 10;
    //总页数
    private int totalPage = 0;

    private List<MessageListBean.EmbeddedBean.JpushMessageLogsBean> notice_list = new ArrayList<>();
    private NoticeAdapter adapter_notice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_message;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected MessagePresenter createPresenter() {
        return new MessagePresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this)
                .titleBar(userMessageToolbar)
                .statusBarDarkFont(true, 0.2f)//当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
                .init();

        userMessageTitle.setText("推送消息");

    }

    @Override
    protected void initDatas() {
        super.initDatas();
        noDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) userMessageRv.getParent(), false);

        ImageView empty_iv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView empty_tv = (TextView) noDataView.findViewById(R.id.empty_tv);

        empty_iv.setImageResource(R.mipmap.empty_default);
        empty_tv.setText("暂无消息！");

        errorView = getLayoutInflater().inflate(R.layout.view_error, (ViewGroup) userMessageRv.getParent(), false);

        ImageView error_iv = (ImageView) errorView.findViewById(R.id.error_img);
        error_iv.setImageResource(R.mipmap.error_default);

        loadingView = getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) userMessageRv.getParent(), false);

        ImageView loading_iv = (ImageView) loadingView.findViewById(R.id.loading_img);

        GlideApp.with(mActivity)
                .asGif()
                .load(R.drawable.loading_default)
                .into(loading_iv);


        initRecyclerView();

        errorView.setOnClickListener(v -> {
            adapter_notice.setEmptyView(loadingView);
            page = 0;
            mPresenter.initMessageData(page, size);
        });

        adapter_notice.setEmptyView(loadingView);

        mPresenter.initMessageData(page, size);
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);

        userMessageRefresh.setOnRefreshListener(this);//刷新监听
        userMessageRefresh.setEnableLoadMore(false);
        userMessageRv.setHasFixedSize(true);
        userMessageRv.setFocusable(false);
        userMessageRv.setLayoutManager(layoutManager);

        adapter_notice = new NoticeAdapter(R.layout.module_mine_item_notice, notice_list);
        adapter_notice.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        adapter_notice.setOnLoadMoreListener(this, userMessageRv);
        userMessageRv.setAdapter(adapter_notice);

        adapter_notice.setOnItemClickListener((adapter, view, position) -> {
            int isRead = adapter_notice.getData().get(position).getReadflag();

            if (isRead == 0) {
                //未读
                mPresenter.readMessage(adapter_notice.getData().get(position).getId(), position);
            }

            //然后跳转相应页面
            String extras = adapter_notice.getData().get(position).getContent();
            toDetailActivity(extras);

        });
    }

    @Override
    public void setMessageData(MessageListBean entity) {
        freshEnd();
        //总页数
        totalPage = entity.getPage().getTotalPages();

        if (totalPage <= 0) {
            userMessageDetail.setVisibility(View.GONE);
            //先设置空布局
            if (page == 0) {
                adapter_notice.replaceData(new ArrayList<>());
                adapter_notice.setEmptyView(noDataView);
                adapter_notice.notifyDataSetChanged();
            } else {
                adapter_notice.setEmptyView(noDataView);
                adapter_notice.notifyDataSetChanged();
            }
        } else {
            userMessageDetail.setVisibility(View.VISIBLE);
            notice_list = entity.get_embedded().getJpushMessageLogs();
            if (page == 0) {
                adapter_notice.setNewData(notice_list);
                //如果数据少 不显示已加载全部
                adapter_notice.disableLoadMoreIfNotFullPage();
            } else {
                adapter_notice.addData(notice_list);

            }
        }

        adapter_notice.loadMoreComplete();


    }

    @Override
    public void setMessageError(String msg) {
        freshEnd();
        userMessageDetail.setVisibility(View.GONE);
        adapter_notice.setEmptyView(errorView);
        adapter_notice.loadMoreFail();
    }

    @Override
    public void readMessageSuccess(int clickPosition) {
        if (clickPosition == -1) {
            //全读
            if (null != adapter_notice) {
                adapter_notice.replaceData(new ArrayList<>());
                adapter_notice.setEmptyView(loadingView);
            }
            page = 0;
            mPresenter.initMessageData(page, size);
        } else {
            adapter_notice.getData().get(clickPosition).setReadflag(1);
            adapter_notice.notifyDataSetChanged();
        }

        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_MESSAGE_POINT));

    }

    @Override
    public void readMessageError(String msg) {

    }

    private void toDetailActivity(String content) {
        JSONObject jsonObject = JSONObject.parseObject(content);
        String json = jsonObject.getString("extras");

        JSONObject extras = JSONObject.parseObject(json);
        String act = extras.getString("act").trim();

        Logger.e("act====" + act);

        if (act.equals("order")) {
            //订单已接单（自提）商家订单完成 订单配送（快递）订单被拒------跳转订单详情
            String id = extras.getString("id");
            RouterCommonUtils.startParameterActivity(RouterIntentConstant.MODULE_SHOPPING_ORDER_DETAIL, "orderId", id);
        } else if (act.equals("coupon")) {
            //优惠券即将失效-------跳转优惠券列表
            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_SHOPPING_COUPON);
        } else if (act.equals("redpackage")) {
            //红包即将失效 充值送红包 分享有礼送红包-------跳转红包列表
            Intent mIntent = new Intent(mActivity, RedPacketActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(mIntent);
        } else if (act.equals("miaosha")) {
            //开抢提醒-------跳转商品详情
            String id = extras.getString("id");
            String url = Constant.HTTP_URL_BASE_HEAD + "gds/goods-sqrs/" + id;
            RouterCommonUtils.startParameterActivity(RouterIntentConstant.MODULE_SHOPPING_GOODS_DETAIL, "url", url);
        } else if (act.equals("alluser")) {
            //营销活动
            String url = extras.getString("url");
            //跳转title
            String title = extras.getString("title");
            if (RxDataTool.isNullString(title)) {
                title = "活动";
            }
            Intent mIntent = new Intent(mActivity, BaseX5WebActivity.class);
            mIntent.putExtra("url", url);
            mIntent.putExtra("title", title);
            startActivity(mIntent);
        } else if (act.equals("express")) {
            //快递收件列表
//            Intent mIntent = new Intent(mActivity, ExpressListActivity.class);
//            mIntent.putExtra("status", 0);
//            startActivity(mIntent);
        } else if (act.equals("express_send_out")) {
            //快递发件列表
//            Intent mIntent = new Intent(mActivity, ExpressListActivity.class);
//            mIntent.putExtra("status", 1);
//            startActivity(mIntent);
        } else if (act.equals("express_send")) {
            //快递寄件记录列表
//            int id = jsonObject.getIntValue("id");
//            Intent mIntent = new Intent(mActivity, SenderRecodeListDetailActivity.class);
//            mIntent.putExtra("id", id);
//            mIntent.putExtra("push", 6);
//            startActivity(mIntent);
        } else if (act.equals("express_sign")) {
//            Intent mIntent = new Intent(mActivity, ExpressListActivity.class);
//            mIntent.putExtra("status", 2);
//            startActivity(mIntent);
        } else {
//            EventBus.getDefault().post(new AppEvent(Config.REFRESH_MAIN_CURRENT));
            finish();
        }


    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (null != adapter_notice) {
            adapter_notice.setEnableLoadMore(false);
            adapter_notice.replaceData(new ArrayList<>());
            adapter_notice.setEmptyView(loadingView);
        }
        page = 0;
        mPresenter.initMessageData(page, size);
        adapter_notice.setEnableLoadMore(true);

    }

    @Override
    public void onLoadMoreRequested() {
        userMessageRefresh.setEnableRefresh(false);
        if (totalPage > 0) {
            if (page < totalPage - 1) {
                page++;
                mPresenter.initMessageData(page, size);
                userMessageRefresh.setEnableRefresh(true);
            } else {
                adapter_notice.loadMoreEnd();
                userMessageRefresh.setEnableRefresh(true);
            }
        }

    }

    private void freshEnd() {
        userMessageRefresh.finishRefresh(200);
    }

    @OnClick({R2.id.user_message_back})
    public void backClick(View view) {
        finish();
    }

    @OnClick({R2.id.user_message_detail})
    public void detailClick(View view) {
        //全选,当有未读消息时，才走接口
        for (int i = 0; i < notice_list.size(); i++) {
            if (notice_list.get(i).getReadflag() == 0) {
                mPresenter.readMessage("", -1);
                break;
            }
        }

    }
}
